﻿using AutoMapper;
using MediatR;
using RBAC.Domain.SmartHealthcare;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using SmartHealthcare.Write.Api.Application.Command.Case;

namespace SmartHealthcare.Write.Api.Application.Handler.Case
{
    /// <summary>
    /// 删除病例
    /// </summary>
    public class DeleteCaseHandler : IRequestHandler<DeleteCaseCommand, APIResult<int>>
    {
        private readonly IBaseRepository<CaseModel> caseRepository;
        private readonly IMapper mapper;
        private readonly ILogger<CreateCaseHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="caseRepository"></param>
        /// <param name="mapper"></param>
        /// <param name="logger"></param>
        public DeleteCaseHandler(IBaseRepository<CaseModel> caseRepository, IMapper mapper, ILogger<CreateCaseHandler> logger)
        {
            this.caseRepository = caseRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 删除病例
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(DeleteCaseCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var model = caseRepository.GetModel(request.Id);
            if (model != null)
            {
                model.IsDeleted = true;
                var r = caseRepository.Update(model);
                if (r > 0)
                {
                    res.Data = r;
                    res.Code = APIEnums.Success;
                    res.Msg = "删除病例成功";
                    logger.LogInformation("删除病例成功");
                    return Task.FromResult(res);
                }
                else
                {
                    res.Data = r;
                    res.Code = APIEnums.Fail;
                    res.Msg = "删除病例失败";
                    logger.LogError("删除病例失败");
                    return Task.FromResult(res);
                }
            }
            else
            {
                res.Data = 0;
                res.Code = APIEnums.Fail;
                res.Msg = "您要删除的病例不存在";
                logger.LogError("删除病例失败");
                return Task.FromResult(res);
            }
        }
    }
}
